package com.school.service.Impl;

import com.school.common.ServiceResultEnum;
import com.school.entity.Goods;
import com.school.mapper.GoodsCategoryMapper;
import com.school.mapper.GoodsMapper;
import com.school.service.GoodsService;
import com.school.util.PageQueryUtil;
import com.school.util.PageResult;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * ClassName: GoodsServiceImpl
 * Package: com.school.service.impl
 * Description:
 *
 * @Author laohe
 * @Create 2025-07-13 9:14
 * @Version 1.0
 */
@Service
public class GoodsServiceImpl implements GoodsService {

    @Resource
    private GoodsMapper goodsMapper;
    @Resource
    private GoodsCategoryMapper goodsCategoryMapper;

    @Override
    public PageResult getGoodsPage(PageQueryUtil pageQueryUtil) {
        List<Goods> list = goodsMapper.findGoodsList(pageQueryUtil);
        int totalCount = goodsMapper.getTotalGoodsCount(pageQueryUtil);
        PageResult pageResult = new PageResult(list, totalCount, pageQueryUtil.getLimit(), pageQueryUtil.getPage());
        return pageResult;
    }

    @Override
    public String saveGoods(Goods goods) {
        // 检查商品分类是否存在
        if (goodsCategoryMapper.selectById(goods.getGoodsCategoryId()) == null) {
            return ServiceResultEnum.GOODS_CATEGORY_ERROR.getResult();
        }

        // 检查同名且同分类的商品是否已存在
        Goods temp = goodsMapper.selectByNameAndCategoryId(goods.getGoodsName(), goods.getGoodsCategoryId());
        if (temp != null) {
            return ServiceResultEnum.SAME_GOODS_EXIST.getResult();
        }

        // 插入商品信息
        if (goodsMapper.insertSelective(goods) > 0) {
            return ServiceResultEnum.SUCCESS.getResult();
        }

        // 数据库操作失败
        return ServiceResultEnum.DB_ERROR.getResult();
    }

}
